package cn.glutnn.service.impl;

import cn.glutnn.entity.Result;
import cn.glutnn.entity.User;
import cn.glutnn.entity.dto.LoginDTO;
import cn.glutnn.entity.dto.PasswordDTO;
import cn.glutnn.entity.dto.RegisterDTO;
import cn.glutnn.mapper.UserMapper;
import cn.glutnn.service.UserService;
import cn.glutnn.utils.JwtUtil;
import cn.glutnn.utils.Md5Util;
import cn.glutnn.utils.ThreadLocalUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (User)表服务实现类
 *
 * @author msh
 * @since 2024-10-24 16:05:22
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result login(LoginDTO loginDTO) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, loginDTO.getUserName());
        User user = getOne(wrapper);
        if (user == null) {
            return Result.error("用户不存在");
        }
        if (!Md5Util.checkPassword(loginDTO.getPassword(), user.getPassword())) {
            return Result.error("密码错误");
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("username", user.getUserName());
        String token = JwtUtil.genToken(map);

        // 将token存入redis
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.set("rxtToken", token);
        return Result.success(token);
    }


    // 修改密码
    @Override
    public Result<User> updatePassword(PasswordDTO passwordDTO) {
        Map o = ThreadLocalUtil.get();
        String username = (String) o.get("username");
        User user = getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, username));

        if (!Md5Util.checkPassword(passwordDTO.getOldPassword(), user.getPassword())) {
            return Result.error("旧密码错误");
        }
        user.setPassword(Md5Util.getMD5String(passwordDTO.getNewPassword()));
        user.setUpdateTime(new Date());
        boolean update = update(user, new UpdateWrapper<User>().eq("user_name", username));
        if (!update) {
            return Result.error("修改密码失败");
        }

        return Result.success();
    }

    @Override
    public Result<User> selectByName() {
        Map o = ThreadLocalUtil.get();
        Object o1 = o.get("username");
        System.out.println(o1);
        User user = getOne(new QueryWrapper<User>().eq("user_name", o1));
        return Result.success(user);
    }

    @Override
    public Result<User> updateByUsername(User user) {
        Map o = ThreadLocalUtil.get();
        Object o1 = o.get("username");
        user.setUserName(o1.toString());
        user.setUpdateTime(new Date());

        boolean update = update(user, new QueryWrapper<User>().eq("user_name", o1));
        if (!update) {
            return Result.error("修改失败");
        }
        return Result.success();
    }

    @Override
    public Result<List<User>> selectALlList() {
        return Result.success(list());
    }

    @Override
    public Result<User> addUser(User user) {
        User user1 = getOne(new QueryWrapper<User>().eq("user_name", user.getUserName()));
        if (user1 != null) {
            return Result.error("用户已存在");
        }

        user.setPassword(Md5Util.getMD5String(user.getPassword()));
        user.setRole("user");

        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setIntegral(0);
        user.setCredit(0);
        boolean save = save(user);
        if (!save) {
            return Result.error("添加失败");
        }
        return Result.success();
    }

    /*
     * 更新用户信息
     * */
    @Override
    public Result<User> updateUser(String username, User user) {
        user.setUpdateTime(new Date());
        user.setUserName(username);
        if (!StringUtils.isEmpty(user.getPassword())) {
            user.setPassword(Md5Util.getMD5String(user.getPassword()));
        }


        boolean update = update(user, new QueryWrapper<User>().eq("user_name", username));

        if (!update) {
            return Result.error("修改失败");
        }
        return Result.success();
    }

    /*
     * 根据id删除用户
     * */
    @Override
    public Result<User> deleteUserByUsername(String username) {
        boolean remove = remove(new QueryWrapper<User>().eq("user_name", username));
        if (!remove) {
            return Result.error("删除失败");
        }
        return Result.success();
    }

    /*
     * 根据用户名查询用户
     * */
    @Override
    public Result<User> selectUserByName(String userName) {

        User user = getOne(new QueryWrapper<User>().eq("user_name", userName));

        return Result.success(user);
    }


    /*
     * 按指定列分页查询所有用户
     * */
    @Override
    public Result<Page<User>> selectAllUserByPage(Integer pageNum) {
        Page<User> userPage = new Page<>(pageNum, 3);
        Page<User> page = page(userPage, new QueryWrapper<User>());
        return Result.success(page);
    }

    /*
     * 根据用户名和其它条件查询用户
     *
     * */
    @Override
    public Result<Page<User>> selectUserByPageAndNameAndOther(Integer pageNum, Integer pageSize, User user) {
        Page<User> userPage = new Page<>(pageNum, pageSize);
        Page<User> page = page(userPage);

        return Result.success(page);
    }

    @Override
    public Result register(RegisterDTO registerDTO) {
        if (!registerDTO.getPassword().equals(registerDTO.getRePassword())) {
            return Result.error("两次密码不一致");
        }
        User user = getOne(new LambdaQueryWrapper<User>().eq(User::getUserName, registerDTO.getUserName()));
        if (user != null) {
            return Result.error("用户已存在");
        }
        User user1 = new User();
        BeanUtils.copyProperties(registerDTO, user1);
        Date date = new Date(System.currentTimeMillis());
//        user1.setCreateTime(date);
        user1.setUpdateTime(date);
        user1.setPassword(Md5Util.getMD5String(registerDTO.getPassword()));
        save(user1);
        return Result.error("注册成功");
    }

    @Override
    public void logout() {
        stringRedisTemplate.delete("rxtToken");
    }


}

